﻿#coding=utf-8

from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.contrib.auth.models import User
from meet001.meetup.models import Group
from meet001.meetup.location import location_code, city_district
import datetime


def search_group(request):
  if request.method != "GET":
    return
  group_name = request.GET['group_name']
  city = request.GET['city']
  district = request.GET['district']
  matched_groups = None
  search_keyword = None
  if city == u'任意' or district == u'任意':
    matched_groups = Group.objects.filter(name__icontains=group_name)
    search_keywords = '' + group_name + '' 
  else:
    matched_groups = Group.objects.filter(name__icontains=group_name,
        location=location_code[(city, district)])
    search_keywords = '' + group_name + ' in ' + city + ' and ' + district + '' 
  matched_groups_info = []
  for group in matched_groups:
    matched_group_info = {}
    matched_group_info['group'] = group
    # Get the next meetup.
    meetups = list(group.meetup_set.order_by('-time_from'))
    next_meetup = None
    past_meetup = []
    now = datetime.datetime.now()
    for meetup in meetups:
      if meetup.time_from> now:
        next_meetup = meetup
      else:
        past_meetup.append(meetup)
    if next_meetup is not None:
      matched_group_info['next_meetup'] = next_meetup
    else:
      matched_group_info['next_meetup'] = ''
    matched_group_info['past_meetups'] = past_meetup
    matched_groups_info.append(matched_group_info)
  return render_to_response('group_search_result.html',
      {'matched_group_num':len(matched_groups),
        'search_keywords':search_keywords,
        'matched_groups_info':matched_groups_info})
